package com.graduation.fq.teacher.process;

import com.graduation.fq.teacher.utils.Const;
import com.graduation.fq.teacher.utils.LoginRegisterIndex;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jifang
 * @version 2016/5/16.
 */
public class LoginRegisterProcess extends BaseProcess {

    private final Map<LoginRegisterIndex, String> urls = new HashMap<>();

    {
        urls.put(LoginRegisterIndex.LOGIN, "/teacher/login.do?name=%s&password=%s");
        urls.put(LoginRegisterIndex.REGISTER, "/teacher/register.do?name=%s&password=%s");
    }

    /**
     * request
     */
    private LoginRegisterIndex index;
    private String name;
    private String password;

    /**
     * response
     */
    private boolean isSuccess;
    private String tId;

    public LoginRegisterProcess(LoginRegisterIndex index, String name, String password) {
        this.index = index;
        this.name = name;
        this.password = password;
    }

    public LoginRegisterIndex getIndex() {
        return index;
    }

    public void setIndex(LoginRegisterIndex index) {
        this.index = index;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public void setSuccess(boolean success) {
        isSuccess = success;
    }

    public String gettId() {
        return tId;
    }

    public void settId(String tId) {
        this.tId = tId;
    }

    @Override
    String getRequestUrl() {
        return String.format(urls.get(getIndex()), getName(), getPassword());
    }

    @Override
    String getParameter() {
        return null;
    }

    @Override
    void onResult(JSONObject object) {
        int statusCode = object.optInt("status");
        setStatus(statusCode);
        if (statusCode == Const.HTTP_SUCCESS) {
            if (getIndex() == LoginRegisterIndex.LOGIN) {
                JSONObject dataObject = object.optJSONObject("data");
                setSuccess(dataObject.optBoolean("is_login"));
                settId(tId = dataObject.optString("id"));
            } else {
                setSuccess(object.optBoolean("data"));
            }
        }
    }
}
